use std::sync::{Arc, Mutex};
use imgui::*;
use native_dialog::FileDialog;
use crate::console::Console;
use crate::config::Config;
use crate::network::ServiceInfo;
use std::collections::HashMap;
use std::time::Instant;
use log::info;

pub struct ButtonAnimation {
    scale: f32,
    state: u8,
    repeat_count: u8,
    is_paused: bool,
    pause_start: Instant,
    last_activity: Instant,
}

impl ButtonAnimation {
    pub fn new() -> Self {
        Self {
            scale: 1.0,
            state: 0,
            repeat_count: 0,
            is_paused: false,
            pause_start: Instant::now(),
            last_activity: Instant::now(),
        }
    }

    pub fn update(&mut self, delta_scale: f32) {
        if self.last_activity.elapsed().as_secs() < 60 {
            return;
        }

        if !self.is_paused {
            match self.state {
                0 => {
                    self.scale = 1.0;
                    self.state = 1;
                }
                1 => {
                    self.scale += delta_scale;
                    if self.scale >= 1.5 {
                        self.state = 2;
                    }
                }
                2 => {
                    self.scale -= delta_scale;
                    if self.scale <= 0.8 {
                        self.state = 1;
                        self.repeat_count += 1;
                        if self.repeat_count >= 2 {
                            self.is_paused = true;
                            self.pause_start = Instant::now();
                        }
                    }
                }
                _ => {}
            }
        } else if self.pause_start.elapsed().as_secs() >= 2 {
            self.is_paused = false;
            self.state = 1;
            self.repeat_count = 0;
        }
    }

    pub fn reset(&mut self) {
        self.scale = 1.0;
        self.state = 0;
        self.repeat_count = 0;
        self.is_paused = false;
        self.last_activity = Instant::now();
    }
}

pub struct SettingWindow {
    button_animation: ButtonAnimation,
    console: Arc<Mutex<Console>>,
    stop_flag: Arc<Mutex<bool>>,
    selected_com_port: Arc<Mutex<String>>,
    online_status: Arc<Mutex<String>>,
    service_statuses: Arc<Mutex<HashMap<String, ServiceInfo>>>,
    config: Config,
    auto_scroll: bool,
    display_pos: [f32; 2],
}

impl SettingWindow {
    pub fn new(
        config: Config,
        console: Arc<Mutex<Console>>,
        online_status: Arc<Mutex<String>>,
        service_statuses: Arc<Mutex<HashMap<String, ServiceInfo>>>,
    ) -> Self {
        Self {
            button_animation: ButtonAnimation::new(),
            console,
            stop_flag: Arc::new(Mutex::new(false)),
            selected_com_port: Arc::new(Mutex::new(String::from("COM1"))),
            online_status,
            service_statuses,
            config,
            auto_scroll: true,
            display_pos: [320.0, 10.0],
        }
    }

    pub fn render(&mut self, ui: &Ui) {
        ui.window("Setting")
            .movable(false)
            .position([10.0, 10.0], Condition::FirstUseEver)
            .size([300.0, 300.0], Condition::FirstUseEver)
            .build(|| {
                ui.text("设置参数");
                ui.separator();
                
                // Display window position
                ui.text(format!(
                    "调试信息窗口位置: X={:.1}, Y={:.1}",
                    self.display_pos[0], self.display_pos[1]
                ));
                
                // Auto-scroll checkbox
                ui.checkbox("自动滚动", &mut self.auto_scroll);

                // Export log button
                if ui.button("导出日志") {
                    self.handle_export_log();
                }
                ui.same_line();

                // Stop button
                if ui.button("停止") {
                    self.handle_stop_button();
                }
                ui.same_line();

                // Update animation and button
                self.handle_animation(ui);
                self.render_update_button(ui);

                // COM port selection
                self.render_com_port_selection(ui);

                // Burn button
                if ui.button("烧录") {
                    self.handle_burn_button();
                }
                ui.same_line();

                // Status display
                self.render_status(ui);
            });
    }

    fn handle_export_log(&mut self) {
        let host = self.config.network.host.clone();
        let port = self.config.network.port;
        let console = self.console.clone();
        
        tokio::spawn(async move {
            match crate::remote::download_remote_log(&host, port, "/var/log/orangepi-cli.log").await {
                Ok(_) => {
                    console.lock().unwrap().append_output("日志文件下载成功".to_string());
                    self.show_message_dialog(true, "下载成功", "日志文件已成功下载");
                },
                Err(e) => {
                    console.lock().unwrap().append_output(format!("下载日志失败: {}", e));
                    self.show_message_dialog(false, "下载失败", &format!("下载日志失败: {}", e));
                },
            }
        });
    }

    fn show_message_dialog(&self, success: bool, title: &str, message: &str) {
        native_dialog::MessageDialog::new()
            .set_type(if success {
                native_dialog::MessageType::Info
            } else {
                native_dialog::MessageType::Error
            })
            .set_title(title)
            .set_text(message)
            .show_alert()
            .unwrap_or_default();
    }

    fn handle_stop_button(&mut self) {
        let mut stop = self.stop_flag.lock().unwrap();
        *stop = true;
        self.console.lock().unwrap().append_output("停止任务!!!".to_string());
    }

    fn handle_animation(&mut self, ui: &Ui) {
        self.button_animation.update(0.001);
        
        // Check for mouse activity
        let window_pos = ui.window_pos();
        let window_size = ui.window_size();
        if ui.is_mouse_hovering_rect(
            window_pos,
            [window_pos[0] + window_size[0], window_pos[1] + window_size[1]],
        ) {
            self.button_animation.reset();
        }
    }

    fn render_update_button(&mut self, ui: &Ui) {
        let scale = self.button_animation.scale;
        ui.set_cursor_pos([
            ui.cursor_pos()[0] + (100.0 * (1.0 - scale)) / 2.0,
            ui.cursor_pos()[1],
        ]);

        if ui.button_with_size("更新", [100.0 * scale, 20.0 * scale]) {
            self.handle_update_button();
        }
    }

    fn handle_update_button(&mut self) {
        *self.stop_flag.lock().unwrap() = false;
        
        if let Ok(Some(file_path)) = FileDialog::new()
            .set_location(&std::env::current_dir().unwrap_or_default())
            .show_open_single_file()
        {
            if let Some(path_str) = file_path.to_str() {
                info!(
                    "Executing command: {} update --source {}",
                    self.config.tool.pkgtool, path_str
                );
                self.console.lock().unwrap().execute_command(
                    &self.config.tool.pkgtool,
                    &["update", "--source", path_str],
                    self.stop_flag.clone(),
                );
            }
        }
    }

    fn render_com_port_selection(&mut self, ui: &Ui) {
        let com_ports = (1..=30).map(|i| format!("COM{}", i)).collect::<Vec<_>>();
        let mut current_port = self.selected_com_port.lock().unwrap().clone();

        ui.set_next_item_width(100.0);
        if let Some(combo) = ui.begin_combo("##com_port", &current_port) {
            for com_port in &com_ports {
                if &current_port == com_port {
                    ui.set_item_default_focus();
                }
                if ui.selectable_config(com_port)
                    .selected(&current_port == com_port)
                    .build()
                {
                    *self.selected_com_port.lock().unwrap() = com_port.clone();
                }
            }
            combo.end();
        }
    }

    fn handle_burn_button(&mut self) {
        *self.stop_flag.lock().unwrap() = false;
        let port = self.selected_com_port.lock().unwrap().clone();
        info!("Executing command: {} burn --port {}", self.config.tool.pkgtool, port);
        self.console.lock().unwrap().execute_command(
            &self.config.tool.pkgtool,
            &["burn", "--port", &port],
            self.stop_flag.clone(),
        );
    }

    fn render_status(&self, ui: &Ui) {
        let status = self.online_status.lock().unwrap();
        const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
        const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];

        if status.starts_with("在线") {
            let green_color = ui.push_style_color(StyleColor::Text, GREEN);
            ui.text(format!("设备状态: {}", *status));
            green_color.pop();
        } else {
            let red_color = ui.push_style_color(StyleColor::Text, RED);
            ui.text(format!("设备状态: {}", *status));
            red_color.pop();
        }

        let statuses_lock = self.service_statuses.lock().unwrap();
        for (_service_key, service_info) in statuses_lock.iter() {
            ui.text(format!(
                "{} 状态: {}",
                service_info.display_name, service_info.status
            ));
        }
    }
}